package cn.knowei.day2.jdbc;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class PropertiesDemo {
    public static String driver;
    public static String url;
    public static String user;
    public static String password;
    static Connection con;
    static Statement stmt;
    static ResultSet rs;
    public static void main(String[] args) {
        //test01();
        try {
            con = DBUtils.getConnection();
            stmt = con.createStatement();
            rs = stmt.executeQuery("SELECT * FROM students");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                DBUtils.close(con, stmt, rs);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }


    }

    private static void test01() {
        Properties properties = new Properties();

        try {
            properties.load(new FileInputStream("db.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("成功");
        }

        driver = properties.getProperty("jdbc.driverClassName");
        url = properties.getProperty("jdbc.url");
        user = properties.getProperty("jdbc.username");
        password = properties.getProperty("jdbc.password");

        System.out.println(driver + "\n" + url + "\n" + user + "\n" + password);

        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try {
            con = DriverManager.getConnection(url, user, password);
            stmt = con.createStatement();
            rs = stmt.executeQuery("SELECT * FROM students") ;

            while (rs.next()) {
                System.out.println(rs.getString("username"));
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            try {
                rs.close();
                stmt.close();
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
